package com.health.controller;

import com.health.constant.MessageConstant;
import com.health.constant.RedisMessageConstant;
import com.health.entity.Result;
import com.health.utils.SMSUtils;
import com.health.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/send4Order.do")
    public Result send4Order(String telephone){
        Integer validateCode= ValidateCodeUtils.generateValidateCode(4);
        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,validateCode.toString());
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        redisTemplate.opsForValue().set(telephone+RedisMessageConstant.SENDTYPE_ORDER,validateCode.toString(),300, TimeUnit.SECONDS);
        return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }

    @PostMapping("/send4Login.do")
    public Result send4Login(String telephone){
        Integer validateCode= ValidateCodeUtils.generateValidateCode(6);
        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,validateCode.toString());
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        redisTemplate.opsForValue().set(telephone+RedisMessageConstant.SENDTYPE_LOGIN,validateCode.toString(),300, TimeUnit.SECONDS);
        return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }
}
